<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <el-card shadow="always">
          <org-tree ref="orgTree" modelType="'dept','community'" @nodeClick="handleNodeClick" @firstNodeClick="handleFirstNodeClick"/>
        </el-card>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-card shadow="always">
          <el-form :model="queryParams" ref="queryForm" v-show="showSearch" label-width="68px" class="form-flex">
            <el-row :gutter="20">
              <el-col :span="6" :xs="24">
                <el-form-item label="路线" prop="pathId">
                  <el-select v-model="queryParams.pathId" style="width: 100%;" placeholder="请选择路线">
                    <el-option
                      v-for="dict in pathOptions"
                      :key="dict.id"
                      :label="dict.pathName"
                      :value="dict.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24">
                <el-form-item label="巡检人" prop="cruiserPersion">
                  <el-input
                    v-model="queryParams.cruiserPersion"
                    placeholder="请输入巡检人"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24">
                <el-form-item label="任务状态" prop="taskState">
                  <el-select v-model="queryParams.taskState" placeholder="请选择任务状态" clearable size="small">
                    <el-option
                      v-for="item in dict.task_state"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" :xs="24">
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['waitress:CruiserTask:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['waitress:CruiserTask:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['waitress:CruiserTask:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['waitress:CruiserTask:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="CruiserTaskList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="路线名称" align="center" prop="pathName" >
                <template slot-scope="scope">
                  <el-link type="primary" @click="clickNo(scope.row)">{{scope.row.pathName}}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="巡逻任务数" align="center" prop="zsl"/> >
              <el-table-column label="巡检开始时间" align="center" prop="cruiserTime"/>
              <el-table-column label="巡检结束时间" align="center" prop="cruiserEndtime"/>
              <el-table-column label="巡检人" align="center" prop="nickName" />
              <el-table-column label="任务状态" align="center" prop="taskState" >
              <template slot-scope="scope">
                {{ dict.label.task_state[scope.row.taskState] }}
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="clickNo(scope.row)">
                  <span v-if="scope.row.statecount!='0'">打卡</span>
                  <span v-else>查看</span>
                  </el-button>
                <!-- <el-button
                  size="mini"
                  type="text"
                  v-if="scope.row.taskState=='10'"
                  icon="el-icon-edit"
                  @click="handleOff(scope.row)"
                  v-hasPermi="['waitress:CruiserTask:updCruiserOff']">巡检打卡</el-button> -->
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"/>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body v-drag-fullscreen>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8" :xs="24">
            <el-form-item label="所属小区" prop="communityId">
              <el-select v-model="form.communityId" style="width: 100%;" placeholder="请选择所属小区">
                <el-option
                  v-for="dict in communityOptions"
                  :key="dict.id"
                  :label="dict.communityName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="路线" prop="pathId">
              <el-select v-model="form.pathId" style="width: 100%;" placeholder="请选择路线">
                <el-option
                  v-for="dict in pathOptions"
                  :key="dict.id"
                  :label="dict.pathName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="巡检开始时间" prop="cruiserTime">
              <el-date-picker
                v-model="form.cruiserTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="巡检结束时间" prop="cruiserEndtime">
              <el-date-picker
                v-model="form.cruiserEndtime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                align="right">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :xs="24">
            <el-form-item label="巡检人" prop="cruiserPersion">
              <el-select v-model="form.cruiserPersion" style="width: 100%;" placeholder="请选择巡检人员">
                <el-option
                  v-for="dict in userOptions"
                  :key="dict.userId.toString()"
                  :label="dict.nickName"
                  :value="dict.userId.toString()"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="8" :xs="24">
            <el-form-item label="任务状态" prop="taskState">
              <el-select v-model="form.taskState" placeholder="请选择任务状态" :disabled="disabled">
                <el-option
                  v-for="item in dict.task_state"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="24" :xs="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="disabled"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <detail ref="detail"/>
    <CruiserTaskForm ref="formRef" @cancel="getList" />
  </div>
</template>

<script>

import { listMixin } from "@/utils/mixins/listMixin";
import { listCruiserTask, delCruiserTask, exportCruiserTask, getCruiserTask , addCruiserTask, updateCruiserTask  } from "@/api/waitress/CruiserTask";
import { listCommunity,getCommunity} from "@/api/property/community";
import { listUser } from "@/api/system/user";
import { listPath } from "@/api/waitress/path";
import CruiserTaskForm from "./form.vue"
import  detail from "./detail";
import { listPathDetail} from "@/api/waitress/PathDetail";

export default {
  name: "CruiserTask",
  mixins:[ listMixin ],
  components:{detail,CruiserTaskForm },
  dicts: [   'task_state',   ],
  data() {
    return {
      // 巡逻任务表格数据
      CruiserTaskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否禁用
      disabled: false,
      communityOptions:[],
      pathOptions:[],
      userOptions:[],
      // 表单参数
      form: {
        pathDetailList: []
      },
      // 表单校验
      rules: {
        communityId: [
          { required: true, message: "所属小区不能为空", trigger: "blur" }
        ],
        pathId: [
          { required: true, message: "路线不能为空", trigger: "blur" }
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        communityId: null,
        pathId: null,
        cruiserTime: null,
        cruiserPersion: null,
        taskState: null,
        deptId: null,
        ancestors: null,
        nodeId:null,
      },
    };
  },
  watch:{
    'form.communityId'(v){
      this.getPath();
      getCommunity(this.form.communityId).then(res=>{
        listUser({'deptId':res.data.deptId}).then(respon =>{
          this.userOptions =respon.rows;
        })
      })

    }
  },
  created() {
    // this.getList();
    listCommunity().then(res=>{
      this.communityOptions = res.rows;
    });
    this.getPath();
  },
  methods: {
    getPath(){
      listPath({'communityId':this.form.communityId}).then(res=>{
        this.pathOptions = res.rows;
      })
    },
    /** 查询巡逻任务列表 */
    getList() {
      this.loading = true;
      listCruiserTask(this.queryParams).then(response => {
        this.CruiserTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if(this.currentNode.modelType == 'community'){
        this.form.communityId = this.currentNode.id
        this.open = true;
      }else {
        this.open = true;
      }
      this.title = "新增巡逻任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      const option = {
          "type":"UPDATE",
          "id": id
      }
      getCruiserTask(option.id).then(response => {
        this.form = response.data;
        if(option.type == 'VIEW'){
          this.title = "查看巡逻任务";
        }else{
          this.title = "修改巡逻任务";
        }
        this.open = true;
      });
    },
    handleNodeClick(node){
      this.currentNode = node;
      this.queryParams.nodeId = node.id
      this.getList()
    },
    handleFirstNodeClick(node){
      this.currentNode = node;
      this.queryParams.nodeId = node.id;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$emit("cancel")
    },
    clickNo(row){
      this.$refs.detail.show({'pathId':row.pathId, 'id': row.id, 'stateCount': row.statecount})
    },
    handleOff(row){
      const id = row.id || this.ids
      const option = {
        "type":"UPDATE",
        "id": id,
        "pathId": row.pathId
      }
      this.$refs.formRef.show(option);
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        communityId: null,
        pathId: null,
        cruiserTime: null,
        cruiserPersion: null,
        taskState: '10',
        deptId: null,
        ancestors: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        cruiserEndtime:null,
      };
      this.resetForm("form");
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除巡逻任务编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCruiserTask(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有巡逻任务数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCruiserTask(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      listPathDetail({'pathId':this.form.pathId}).then(response => {
        this.form.pathDetailList = response.rows.map(item => item.placeId)
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateCruiserTask(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.cancel();
                this.getList();
              });
            } else {
              addCruiserTask(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.cancel();
                this.getList();
              });
            }
          }
        });
      });
    }
  }
};
</script>
